<!-- 用户管理 -->
<template>
	<div class="bg-ff commonality">
		<el-row :gutter="40">
			<!--组织数据-->
			<el-col :span="4" :xs="24">
				<div class="head-container">
					<el-input clearable placeholder="请输入组织名称" prefix-icon="el-icon-search" style="margin-bottom: 10px" v-model="deptName" />
				</div>
				<div class="head-container">
					<el-tree
						:data="deptOptions"
						:expand-on-click-node="false"
						:filter-node-method="filterNode"
						:props="{ label: 'name', value: 'id' }"
						@node-click="handleNodeClick"
						default-expand-all
						ref="tree"
					/>
				</div>
			</el-col>

			<el-col :span="20" :xs="24">
				<el-form :inline="true" :model="queryParams" label-width="80px" ref="queryForm">
					<el-form-item class="mr-10" label="登录名" prop="username">
						<el-input @keyup.enter.native="handleQuery" clearable placeholder="请输入登录名" v-model="queryParams.username" />
					</el-form-item>
					<el-form-item class="mr-10" label="姓名" prop="nickname">
						<el-input @keyup.enter.native="handleQuery" clearable placeholder="请输入姓名" v-model="queryParams.nickname" />
					</el-form-item>
					<el-form-item class="mr-10" label="手机号码" prop="mobile">
						<el-input @keyup.enter.native="handleQuery" clearable maxlength="11" placeholder="请输入手机号码" v-model="queryParams.mobile" />
					</el-form-item>
					<el-form-item label="用户状态" prop="status">
						<el-select clearable placeholder="请选择用户状态" v-model="queryParams.status">
							<el-option label="全部" value />
							<el-option label="正常" value="1" />
							<el-option label="停用" value="0" />
						</el-select>
					</el-form-item>
					<el-form-item label="角色" prop="roleIds">
						<el-select clearable placeholder="请选择角色" v-model="queryParams.roleIds">
							<el-option :key="item.id" :label="item.name" :value="item.id.toString()" v-for="item in roleOptions" />
						</el-select>
					</el-form-item>
					<el-form-item label="流程角色" prop="job">
						<el-select clearable placeholder="请选择流程角色" v-model="queryParams.job">
							<el-option :key="item.value" :label="item.label" :value="item.value" v-for="item in jobOptions"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item>
						<el-button @click="handleQuery" icon="el-icon-search" type="primary">搜索</el-button>
						<el-button @click="handleReset" icon="el-icon-refresh">重置</el-button>
					</el-form-item>
				</el-form>

				<div class="mb-10">
					<el-button @click="handleAdd" icon="el-icon-plus" plain type="primary">新增</el-button>
					<el-button @click="handleDelete" icon="el-icon-delete" plain style="margin-left:15px" type="danger">删除</el-button>
				</div>

				<el-table
					:data="pageList"
					@selection-change="handleSelectionChange"
					border
					element-loading-spinner="el-icon-loading"
					element-loading-text="数据载入中"
					v-loading="loading"
				>
					<el-table-column align="center" type="selection" width="50" />
					<el-table-column align="center" label="登录名" prop="username" />
					<el-table-column align="center" label="姓名" prop="nickname" />
					<!-- <el-table-column align="center" label="性别" prop="job">
            <template slot-scope="scope">
              <span v-if="scope.row.job===1">男</span>
              <span v-if="scope.row.job===2">女</span>
              <span v-if="scope.row.job===0">未知</span>
            </template>
					</el-table-column>-->
					<el-table-column align="center" label="组织" prop="deptName">
						<template slot-scope="scope">{{scope.row.deptId === '0' ? '特区建工' : scope.row.deptName}}</template>
					</el-table-column>
					<el-table-column align="center" label="角色名称" prop="roleNames" />
					<el-table-column align="center" label="手机号码" prop="mobile" />
					<el-table-column align="center" label="流程角色">
						<template slot-scope="{row}">{{jobMap[row.job]}}</template>
					</el-table-column>
					<el-table-column align="center" label="系统用户">
						<template slot-scope="{row}">{{row.isSysUser === 0 ? '是' : '否'}}</template>
					</el-table-column>
					<el-table-column align="center" label="状态" width="75">
						<template slot-scope="scope">
							<el-switch :active-value="0" :inactive-value="1" @change="handleStatusChange(scope.row)" v-model="scope.row.status" />
						</template>
					</el-table-column>

					<el-table-column align="center" label="操作" width="240">
						<template slot-scope="scope">
							<el-button @click.stop="handleUpdate(scope.row)" circle icon="el-icon-edit" plain type="primary" />
							<el-button @click.stop="handleDelete(scope.row)" circle icon="el-icon-delete" plain type="danger" />
							<el-button @click.stop="handleResetPassword(scope.row)" circle icon="el-icon-key" plain type="info" />
						</template>
					</el-table-column>
				</el-table>

				<pagination
					:limit.sync="pagination.size"
					:page.sync="pagination.current"
					:total="pagination.total"
					@pagination="handleQuery"
					v-show="pagination.total>0"
				/>
			</el-col>
		</el-row>
		<!-- 新增或修改参数配置对话框 -->
		<el-dialog :close-on-click-modal="false" :title="dialog.title" :visible.sync="dialog.visible" width="800px">
			<el-form :model="form" :rules="rules" class="flex-wrap" label-width="140px" ref="form">
				<el-form-item class="w50" label="登录名" prop="username">
					<el-input :disabled="form.id !== undefined" placeholder="请输入登录名" v-model="form.username" />
				</el-form-item>
				<el-form-item class="w50" label="登录密码" prop="password" v-if="dialog.flag===0">
					<el-input placeholder="请输入登录密码" type="text" v-model="form.password" />
				</el-form-item>
				<el-form-item class="w50" label="姓名" prop="nickname">
					<el-input placeholder="请输入姓名" v-model="form.nickname" />
				</el-form-item>

				<el-form-item class="w50" label="所属单位" prop="deptId">
					<!-- <tree-select :options="deptOptions" placeholder="请选择所属单位" v-model="form.deptId" /> -->
					<el-cascader
						:options="deptOptions"
						:props="{ emitPath: false, checkStrictly: true, label: 'name', value: 'id' }"
						clearable
						filterable
						placeholder="请选择所属单位"
						style="width:100%"
						v-model="form.deptId"
					></el-cascader>
				</el-form-item>

				<el-form-item class="w50" label="流程角色">
					<el-select clearable placeholder="请选择" v-model="form.job">
						<el-option :key="item.value" :label="item.label" :value="item.value" v-for="item in jobOptions"></el-option>
					</el-select>
				</el-form-item>

				<el-form-item class="w50" label="角色" prop="roleIds">
					<el-select multiple placeholder="请选择角色" style="width: 100%" v-model="form.roleIds">
						<el-option :key="item.id" :label="item.name" :value="item.id.toString()" v-for="item in roleOptions" />
					</el-select>
				</el-form-item>
				<el-form-item class="w50" label="手机号码" prop="mobile">
					<el-input maxlength="11" placeholder="请输入手机号码" v-model="form.mobile" />
				</el-form-item>
				<el-form-item class="w50" label="邮箱" prop="email">
					<el-input maxlength="50" placeholder="请输入邮箱" v-model="form.email" />
				</el-form-item>
				<el-form-item class="w50" label="序号" prop="sortNo">
					<el-input maxlength="50" placeholder="请序号" v-model="form.sortNo" />
				</el-form-item>

				<el-form-item class="w50" label="系统用户">
					<el-radio-group v-model="form.isSysUser">
						<el-radio-group v-model="form.isSysUser">
							<el-radio :label="0">是</el-radio>
							<el-radio :label="1">否</el-radio>
						</el-radio-group>
					</el-radio-group>
				</el-form-item>

				<el-form-item class="w50" label="状态">
					<el-radio-group v-model="form.status">
						<el-radio-group v-model="form.status">
							<el-radio :label="0">正常</el-radio>
							<el-radio :label="1">停用</el-radio>
						</el-radio-group>
					</el-radio-group>
				</el-form-item>

				<el-form-item class="w50" label="默认处理人">
					<el-radio-group v-model="form.defaultHandler">
						<el-radio-group v-model="form.defaultHandler">
							<el-radio :label="1">是</el-radio>
							<el-radio :label="0">否</el-radio>
						</el-radio-group>
					</el-radio-group>
				</el-form-item>

				<el-form-item class="w100" label="备注">
					<el-input placeholder="请输入内容" type="textarea" v-model="form.remark" />
				</el-form-item>
			</el-form>
			<div class="dialog-footer" slot="footer">
				<el-button @click="handleSubmit" type="primary">确 定</el-button>
				<el-button @click="dialog.visible=false">取 消</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import DictApi from '../dict/api'
import RoleApi from '../role/api'
import DeptApi from '../dept/api'
import Api from './api'
// import { rsa } from '@utils/security'
import regExpList from '@utils/base/regExp'
export default {
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中用户数组
      ids: [],
      queryParams: {
        username: undefined,
        nickname: undefined,
        mobile: undefined,
        status: undefined
      },
      pagination: {
        current: 1,
        size: 10,
        total: 0
      },
      pageList: [],
      dialog: {
        title: undefined,
        visible: false,
        flag: 0
      },
      // 组织名称
      deptName: undefined,
      // 组织树选项
      deptOptions: undefined,
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {
        roleIds: []
      },
      // 表单校验
      rules: {
        username: [{ required: true, message: '登录名不能为空', trigger: 'blur' }],
        nickname: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
        password: [{ required: true, message: '登录密码不能为空', trigger: 'blur' }],
        job: [{ required: true, message: '流程角色不能为空', trigger: 'blur' }],
        roleIds: [{ required: true, message: '用户角色不能为空', trigger: 'blur' }],
        deptId: [{ required: true, message: '所属单位不能为空', trigger: 'blur' }],
        // email: [{ required: true, type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }],
        mobile: [{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur' }]
      },
      jobOptions: [],
      dictQueryParams: {
        size: 100,
        current: 1,
        name: undefined,
        dictCode: undefined,
        queryMode: '0'
      }
    }
  },
  watch: {
    // 根据名称筛选组织树
    deptName(val) {
      this.$refs.tree.filter(val)
    }
  },
  computed: {
    jobMap() {
      return this.jobOptions.reduce((obj, item) => {
        obj[item.value] = item.label
        return obj
      }, {})
    }
  },
  created() {
    this.handleQuery().finally(() => {
      // 获取角色、组织下拉选项
      this.loadRoleOptions()
      this.loadDeptOptions()
      // this.getJobOptions()
    })
  },
  methods: {
    // 获取职位数据
    getJobOptions() {
      this.dictQueryParams.dictCode = 'position'
      DictApi.getDictItems(this.dictQueryParams).then(data => {
        this.jobOptions = data.records.map(item => {
          return { value: item.value, label: item.name }
        })
      })
    },
    // 查询用户列表
    handleQuery() {
      const roleIds = this.queryParams.roleIds ? [this.queryParams.roleIds] : []
      this.queryParams.current = this.pagination.current
      this.queryParams.size = this.pagination.size
      return Api.getUserList({ ...this.queryParams, roleIds }).then(data => {
        this.pageList = data.records
        this.pagination.total = data.total
      }).finally(() => { this.loading = false })
    },
    // 重置搜索条件
    handleReset() {
      this.pagination = { current: 1, size: 10, total: 0 }
      this.queryParams = {
        username: undefined,
        mobile: undefined
      }
      this.handleQuery()
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) {
        return true
      }
      return data.name.includes(value)
    },
    // 组织节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id
      this.pagination.current = 1
      this.handleQuery()
    },
    // 用户状态修改
    handleStatusChange(row) {
      const { status } = row
      const text = status === 0 ? '启用' : '停用'
      this.$confirm(`确认要${text}${row.username}用户吗?`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        Api.addOrUpdateUser({ ...row, status }).then(() => {
          this.$message.success(`${text}成功`)
        })
      }).catch(() => {
        row.status = row.status === 0 ? 1 : 0
      })
    },
    // 勾选表格用户
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
    },
    // 增加用户
    async handleAdd() {
      this.resetForm()
      this.dialog = {
        title: '新增用户',
        visible: true,
        flag: 0
      }
    },
    // 修改用户
    async handleUpdate(row) {
      this.resetForm()
      this.dialog = {
        title: '修改用户',
        visible: true,
        flag: 1
      }
      // 获取用户详情
      Api.getUserDetail({ id: row.id }).then(res => {
        this.form = res.data
      })
    },
    handleSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          // 防重点
          if (this.submitSign) return
          this.submitSign = true

          const id = this.form.id
          // id 不为undefined 代表修改
          if (id !== undefined) {
            Api.modifyUsers(this.form).then(() => {
              this.$message.success('修改成功')
              this.dialog.visible = false
              this.handleQuery()
            }).finally(() => {
              this.submitSign = null
            })
            // 否则代表新增
          } else {
            Api.addOrUpdateUser({
              ...this.form,
              // password: rsa.encrypt(this.form.password),
              iv: 'z^jas808!~@aa$*'
            }).then(() => {
              this.$message.success('新增成功')
              this.dialog.visible = false
              this.handleQuery()
            }).finally(() => {
              this.submitSign = null
            })
          }
        }
      })
    },
    // 删除用户
    handleDelete(row) {
      const ids = row.id || this.ids
      if (!ids.length) {
        this.$message.warning('请勾选要删除的用户！')
        return
      }
      this.$confirm('是否确认删除选中的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        Api.removeUsers(ids).then(() => {
          this.$message.success('删除成功')
          this.handleQuery()
        })
      }).catch(() =>
        this.$message.info('已取消删除')
      )
    },
    // 修改密码
    handleResetPassword(row) {
      this.$prompt(`请输入${row.username}的新密码`, '提示', {
        onfirmButtonText: '确定',
        inputPlaceholder: '请输入新密码（必须包含数字、大小写字母，且至少八位）',
        inputPattern: regExpList.strongPwd,
        inputErrorMessage: '密码格式不正确',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: (value) => {
          if (!value || value.trim().length < 1) {
            return '请填写新密码'
          }
        }
      }).then(({ value }) => {
        Api.addOrUpdateUser({
          ...row,
          iv: 'z^jas808!~@aa$*',
          password: value
          // password: rsa.encrypt(value)
        }).then(() => {
          this.$message.success(`修改成功，新密码是：${value}`)
        })
      }).catch(() => {
        return false
      })
    },
    // 获取角色列表
    loadRoleOptions() {
      RoleApi.getRoleList({ queryMode: '0' }).then(data => {
        this.roleOptions = data.records
      })
    },
    // 获取组织tree
    loadDeptOptions() {
      DeptApi.getDeptList({ queryMode: '1' }).then(data => {
        this.deptOptions = data.records
      })
    },
    // 表单重置
    resetForm() {
      this.form = {
        id: undefined,
        deptId: undefined,
        username: undefined,
        nickname: undefined,
        mobile: undefined,
        email: undefined,
        job: undefined,
        status: 1,
        defaultHandler: 1,
        isSysUser: 0,
        remark: undefined,
        roleIds: []
      }
      if (this.$refs.form) {
        this.$refs.form.resetFields()
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.user-container {
	&__form {
		.warning-row {
			background: oldlace;
		}
		.success-row {
			background: #f0f9eb;
		}
	}
}
</style>
